<?

abstract class Wlib_Mail_AbstractMailEvent
{
    protected $_tplViewHelper = null;

    protected $_mailData = null;

    protected $_httpDomain = null;

    protected $_defaultFromEmailParams = null;

    protected $_emailSubject = null;

    protected $_eventName = null;

    protected $_mailer = null;

    protected $_mailerOptions = null;

    protected $_viewResourceRenderer = null;

    protected $_subscriberId = null;

    static protected $_defaultOptions = null;

    public function __construct($options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        } elseif ($options instanceof Zend_Config) {
            $this->setConfig($options);
        }

        $this->init();
    }

    public function setConfig(Zend_Config $config)
    {
        return $this->setOptions($config->toArray());
    }

    public function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (method_exists($this, $method)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    public function init()
    {
    }

    public function setMailData($mailData)
    {
        $this->_mailData = $mailData;
        return $this;
    }

    public function getMailData()
    {
        return $this->_mailData;
    }

    public function setDefaultFromEmailParams($defaultFromEmailParams)
    {
        $this->_defaultFromEmailParams = $defaultFromEmailParams;
        return $this;
    }

    public function getDefaultFromEmailParams()
    {
        if(null === $this->_defaultFromEmailParams) {
            $defaultFromEmailParams = self::getDefaultOption('defaultFromEmailParams');
            if($defaultFromEmailParams) {
                $this->setDefaultFromEmailParams($defaultFromEmailParams);
            }
        }

        return $this->_defaultFromEmailParams;
    }

    public function setMailer($mailer)
    {
        $this->_mailer = $mailer;
        return $this;
    }

    public function getMailer()
    {
        if(null === $this->_mailer) {
            $mailerOptions = $this->getMailerOptions();
            $this->setMailer(
                new Wlib_Mail_Mailer($mailerOptions)
            );
        }

        return $this->_mailer;
    }

    public function getMailerOptions()
    {
        if(null === $this->_mailerOptions) {
            $mailerOptions = self::getDefaultOption('mailer');
            if($mailerOptions) {
                $this->setMailerOptions($mailerOptions);
            }
        }

        return $this->_mailerOptions;
    }

    public function setMailerOptions($mailerOptions)
    {
        $this->_mailerOptions = $mailerOptions;
        return $this;
    }

    public function setEmailSubject($emailSubject)
    {
        $this->_emailSubject = $emailSubject;
        return $this;
    }

    public function getEmailSubject()
    {
        return $this->_emailSubject;
    }

    public function mail($toEmail = null, $toName = null)
    {

        if(!$this->checkEventActivity()) {
            return false;
        }

        $mailData = $this->getMailData();

        if(null === $toEmail) {
            $toEmail = isset($mailData['toEmail']) ? $mailData['toEmail'] : '';
        }

        if(null === $toName) {
            $toName = isset($mailData['toName']) ? $mailData['toName'] : '';
        }


        $defaultFromParams = $this->getDefaultFromEmailParams();

        $fromName = isset($mailData['fromName']) ? $mailData['fromName'] : $defaultFromParams['fromName'];
        $fromEmail = isset($mailData['fromEmail']) ? $mailData['fromEmail'] : $defaultFromParams['fromEmail'];

        $viewVars = $this->_prepareViewVars($mailData);

        $viewResourceRenderer = $this->getViewResourceRenderer();
        $viewResourceRenderer->assignViewVars($viewVars);

        $subject = $viewResourceRenderer->getView()->translate($this->getEmailSubject());

        $this->preRenderText();
        $htmlText = $viewResourceRenderer->render();

        $mailer = $this->getMailer();
        $mailer->send($toEmail, $toName, $subject, $htmlText, $fromEmail, $fromName);
    }

    /**
     * Для переопределения в классах-наследниках
     * Вызывает перен ренедерингом текста письма из шаблона.
     * Возможно использовать для переопределения/добавления некоторых переменных письма
     */
    public function preRenderText(){}

    public function _prepareViewVars($mailData)
    {
        $viewVars = self::recursiveEscape($mailData);

        return $viewVars;
    }

    static public function recursiveEscape($objects)
    {
        if(is_array($objects) || $objects instanceof ArrayIterator) {
            foreach ($objects as $key=>$oObject) {
                $objects[$key] = self::recursiveEscape($oObject);
            }
        } else {
            $objects = htmlspecialchars($objects);
        }

        return $objects;
    }

    public static function getDefaultOptions()
    {
        return self::$_defaultOptions;
    }

    public static function setDefaultOptions($defaultOptions)
    {
        self::$_defaultOptions = $defaultOptions;
    }

    public static function getDefaultOption($name)
    {
        if(isset(self::$_defaultOptions[$name])) {
            return self::$_defaultOptions[$name];
        }
        return null;
    }

    public static function setDefaultOption($name, $value)
    {
        self::$_defaultOptions[$name] = $value;
    }

    /**
     * @return Wlib_View_ResourceRenderer
     */
    public function getViewResourceRenderer()
    {
        if(null === $this->_viewResourceRenderer) {
            $viewResourceRenderer = new Wlib_View_ResourceRenderer($this);
            $this->setViewResourceRenderer($viewResourceRenderer);
        }
        return $this->_viewResourceRenderer;
    }

    public function setViewResourceRenderer($viewResourceRenderer)
    {
        $this->_viewResourceRenderer = $viewResourceRenderer;
        return $this;
    }

    public function checkEventActivity()
    {
        $userEventDbMapper = new PersonalConfig_Model_DbMapper_Noties();
        return $userEventDbMapper->checkUserEvent($this->_eventName, $this->getSubscriberId());
    }

    public function setSubscriberId($subscriberId) {
        $this->_subscriberId = $subscriberId;
    }

    public function getSubscriberId() {
        return $this->_subscriberId;
    }

}
